<?php

/**
 * User:ayou chow
 * Date: 2019-12-09
 * Time: 15:52
 */

namespace app\admin\controller;


use app\common\model\AdsModel;
use app\common\model\LiveStoreModel;
use think\facade\Request;

class AdsController extends BaseController
{
    /**
     * 默认图像
     * @return mixed
     */
    public function avatar()
    {
        return $this->fetch();
    }

    public function avatarAdd()
    {
        if ($this->request->isAjax()) {
            if (!$title = trim($this->post('title', ''))) {
                return static::bulidFail('标题不能为空');
            }

            if (!in_array($sex = $this->post('sex'), ['1', '2'])) {
                return static::bulidFail('性别错误');
            }

            if (!in_array($role_type = $this->post('role_type'), ['1', '2'])) {
                return static::bulidFail('权限角色错误');
            }

            if (!$image_url = trim($this->post('image_url', ''))) {
                return static::bulidFail('头像不能为空');
            }

            if (!filter_var($image_url, FILTER_VALIDATE_URL)) {
                return static::bulidFail('头像地址格式错误');
            }

            $model             = new AdsModel();
            $model->title      = $title;
            $model->sex        = $sex;
            $model->role_type  = $role_type;
            $model->image_url  = $image_url;
            $model->start_time = time();
            $model->end_time   = $model->start_time;
            $model->equipment  = 0;
            $model->type       = 9;

            if (!$model->save()) {
                return static::bulidFail();
            }

            $this->addAdminLog("添加头像配置，ID：{$model->id}");

            return static::bulidSuccess();
        }
        return $this->fetch();
    }

    public function avatarEdit()
    {
        if (!$id = $this->get('id')) {
            return static::bulidFail('ID错误');
        }

        if (!$model = AdsModel::field('*')->where('id', $id)->find()) {
            return static::bulidFail('该头像配置不存在');
        }

        if ($this->request->isAjax()) {
            if (!$title = trim($this->post('title', ''))) {
                return static::bulidFail('标题不能为空');
            }

            if (!in_array($sex = $this->post('sex'), ['1', '2'])) {
                return static::bulidFail('性别错误');
            }

            if (!in_array($role_type = $this->post('role_type'), ['1', '2'])) {
                return static::bulidFail('权限角色错误');
            }

            if (!$image_url = trim($this->post('image_url', ''))) {
                return static::bulidFail('头像不能为空');
            }

            if (!filter_var($image_url, FILTER_VALIDATE_URL)) {
                return static::bulidFail('头像地址格式错误');
            }

            $model->title     = $title;
            $model->sex       = $sex;
            $model->role_type = $role_type;
            $model->image_url = $image_url;

            if (!$model->save()) {
                return static::bulidFail();
            }
            $this->addAdminLog("编辑头像配置，ID：{$model->id}");
            return static::bulidSuccess();
        }

        return $this->assign(['adsInfo' => $model])->fetch();
    }

    /**
     * 广告配置
     * @return mixed
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            $model = AdsModel::field('*');
            if ($equipment = trim($this->get('equipment', ''))) {
                $model = $model->where('equipment', $equipment);
            }

            if ($type = trim($this->get('type', ''))) {
                $model = $model->where('type', $type);
            } else {
                $model = $model->whereIn('type', array_keys(AdsModel::TYPE_CATE_B));
            }

            if (in_array($status = trim($this->get('status', '')), ['0', '1'])) {
                $model = $model->where('status', $status);
                if ($status == 1) {
                    $model = $model->where('start_time', '<=', time());
                    $model = $model->where('end_time', '>=', time());
                }

                if ($status == 0) {
                    $model = $model->where('start_time', '>', time());
                    $model = $model->where('end_time', '<=', time());
                }
            }

            if ($operator = trim($this->get('operator', ''))) {
                $model = $model->whereLike('operator', $operator . '%');
            }

            if ($title = trim($this->get('title', ''))) {
                $model = $model->whereLike('title', $title . '%');
            }

            $list = $model->order('id', 'desc')
                ->page((int)$this->get('page', 1), (int)$this->get('limit', 20))
                ->select()->each(function ($query) {
                    if ($query->start_time) {
                        $query->start_time = date('Y-m-d H:i:s', $query->start_time);
                    } else {
                        $query->start_time = '';
                    }

                    if ($query->end_time) {
                        $query->end_time = date('Y-m-d H:i:s', $query->end_time);
                    } else {
                        $query->end_time = '';
                    }
                })
                ->toArray();

            foreach ($list as $k => $v) {
                if (strtotime($v['end_time']) < time()) {
                    $list[$k]['status'] = 2; //失效
                }
            }

            return json([
                'count' => $model->count(),
                'list'  => $list,
                'code'  => 0,
                'now_time' => time(),
            ]);
        }

        return $this->assign([
            'type_cate' => AdsModel::TYPE_CATE_B,
            'type_json' => json_encode(AdsModel::TYPE_CATE_B, JSON_UNESCAPED_UNICODE),
            'now_time' => time(),
        ])->fetch();
    }

    public function add()
    {
        if ($this->request->isAjax()) {
            if (!$title = trim($this->post('title', ''))) {
                return static::bulidFail('广告标题不能为空');
            }

            if (mb_strlen($title) > 12) {
                return static::bulidFail('广告标题不能超过12个字符');
            }

            if (!$equipment = trim($this->post('equipment', ''))) {
                return static::bulidFail('请选择显示端');
            }

            if (!in_array($equipment, [1, 2])) {
                return static::bulidFail('显示端错误');
            }

            if (!$jump_type = trim($this->post('jump_type', ''))) {
                return static::bulidFail('请选择链接类型');
            }

            if (!in_array($jump_type, [1, 2, 3])) {
                return static::bulidFail('链接类型错误');
            }

            if (!$type = trim($this->post('type', ''))) {
                return static::bulidFail('请选择广告位置');
            }

            if (!in_array($type, array_keys(AdsModel::TYPE_CATE_B))) {
                return static::bulidFail('广告位置错误');
            }

            if (!in_array($status = trim($this->post('status', '')), ['0', 1])) {
                return static::bulidFail('启用状态错误');
            }

            if (!$start_time = trim($this->post('start_time', ''))) {
                return static::bulidFail('请选择开始时间');
            }

            if (!$end_time = trim($this->post('end_time', ''))) {
                return static::bulidFail('请选择结束时间');
            }

            if (!$start_time = strtotime($start_time)) {
                return static::bulidFail('开始时间错误');
            }

            if (!$end_time = strtotime($end_time)) {
                return static::bulidFail('结束时间错误');
            }

            if ($end_time <= $start_time) {
                return static::bulidFail('结束时间必须大于开始时间');
            }

            if ($image_url = trim($this->post('image_url', ''))) {
                if (!filter_var($image_url, FILTER_VALIDATE_URL) && $type != 12) {
                    return static::bulidFail('图片地址错误');
                }
            }

            if ($store_id = $this->post('store_id', '', 'intval')) {
                if (!is_numeric($type)) {
                    return static::bulidFail('商品id填写错误');
                }
                // 查询商品是否存在
                if (!LiveStoreModel::field('id')->get($store_id)) {
                    return static::bulidFail('商品ID对应的商品信息不存在，请更换');
                }
            }

            if (AdsModel::field('id')->where('title', $title)->find()) {
                return static::bulidFail('标题已存在 请勿重复添加');
            }


            $model             = new AdsModel();
            $model->title      = $title;
            $model->type       = $type;
            $model->equipment  = $equipment;
            $model->jump_type  = $jump_type;
            $model->start_time = $start_time;
            $model->end_time   = $end_time;
            $model->image_url  = $image_url;
            $model->jump_url   = trim($this->post('jump_url', ''));
            $model->store_id  = $store_id;
            $model->operator   = $this->admin_name;
            $model->match_id   = $this->post('match_id', 0);
            $model->sport_id   = $this->post('sport_id', 0);
            $model->sort   = $this->post('sort', 0);
            $model->sem_image_url = trim($this->post('sem_image_url', ''));

            if (!$model->save()) {
                return static::bulidFail('添加失败');
            }

            $this->addAdminLog("添加广告，ID：{$model->id}");

            return static::bulidSuccess([], '添加成功');
        }
        return $this->assign([
            'type_cate' => AdsModel::TYPE_CATE_B,
        ])->fetch();
    }

    public function edit()
    {
        if (!($id = $this->get('id', '')) || !is_numeric($id)) {
            return static::bulidFail('ID错误');
        }

        if (!$model = AdsModel::where('id', $id)->find()) {
            return static::bulidFail('不存在的广告');
        }

        if ($this->request->isAjax()) {
            if (!$title = trim($this->post('title', ''))) {
                return static::bulidFail('广告标题不能为空');
            }

            if (mb_strlen($title) > 12) {
                return static::bulidFail('广告标题不能超过12个字符');
            }

            if (!$equipment = trim($this->post('equipment', ''))) {
                return static::bulidFail('请选择显示端');
            }

            if (!in_array($equipment, [1, 2])) {
                return static::bulidFail('显示端错误');
            }

            if (!$jump_type = trim($this->post('jump_type', ''))) {
                return static::bulidFail('请选择链接类型');
            }

            if (!in_array($jump_type, [1, 2, 3])) {
                return static::bulidFail('链接类型错误');
            }

            if (!$type = trim($this->post('type', ''))) {
                return static::bulidFail('请选择广告位置');
            }

            if (!in_array($type, array_keys(AdsModel::TYPE_CATE_B))) {
                return static::bulidFail('广告位置错误');
            }

            if (!in_array($status = trim($this->post('status', '')), ['0', 1])) {
                return static::bulidFail('启用状态错误');
            }

            if (!$start_time = trim($this->post('start_time', ''))) {
                return static::bulidFail('请选择开始时间');
            }

            if (!$end_time = trim($this->post('end_time', ''))) {
                return static::bulidFail('请选择结束时间');
            }

            if (!$start_time = strtotime($start_time)) {
                return static::bulidFail('开始时间错误');
            }

            if (!$end_time = strtotime($end_time)) {
                return static::bulidFail('结束时间错误');
            }

            if ($end_time <= $start_time) {
                return static::bulidFail('结束时间必须大于开始时间');
            }

            if ($image_url = trim($this->post('image_url', ''))) {
                if (!filter_var($image_url, FILTER_VALIDATE_URL) && $type != 12) {
                    return static::bulidFail('图片地址错误');
                }
            }
            if ($store_id = $this->post('store_id', '', 'intval')) {
                if (!is_numeric($type)) {
                    return static::bulidFail('商品id填写错误');
                }
                // 查询商品是否存在
                if (!LiveStoreModel::field('id')->get($store_id)) {
                    return static::bulidFail('商品ID对应的商品信息不存在，请更换');
                }
            }

            if ($tempModel = AdsModel::field('id')->where('title', $title)->find()) {
                if ($tempModel->id != $id) {
                    return static::bulidFail('标题已存在');
                }
            }

            $model->title      = $title;
            $model->type       = $type;
            $model->equipment  = $equipment;
            $model->status     = $status;
            $model->jump_type  = $jump_type;
            $model->start_time = $start_time;
            $model->end_time   = $end_time;
            $model->image_url  = $image_url;
            $model->jump_url   = trim($this->post('jump_url', ''));
            $model->store_id   = $store_id;
            $model->operator   = $this->admin_name;
            $model->match_id   = $this->post('match_id', 0);
            $model->sport_id   = $this->post('sport_id', 0);
            $model->sort   = $this->post('sort', 0);
            $model->sem_image_url = trim($this->post('sem_image_url', ''));

            if (!$model->save()) {
                return static::bulidFail('编辑失败');
            }

            $this->addAdminLog("编辑了广告 ID：{$model->id}");

            return static::bulidSuccess([], '编辑成功');
        }

        return $this->assign([
            'model'     => $model->toArray(),
            'type_cate' => AdsModel::TYPE_CATE_B,
        ])->fetch();
    }

    public function enable()
    {
        if (!($id = $this->post('id')) || !is_numeric($id)) {
            return static::bulidFail('ID错误');
        }

        if (!in_array($status = trim($this->post('status', '')), ['0', 1])) {
            return static::bulidFail();
        }

        if (!$model = AdsModel::where('id', $id)->find()) {
            return static::bulidFail();
        }

        $model->status   = $status;
        $model->operator = $this->admin_name;
        if (!$model->save()) {
            return static::bulidFail();
        }

        $log_txt = $model->status == 1 ? '启用' : '禁用';
        $this->addAdminLog("设置广告{$log_txt}，ID：{$model->id}");

        return static::bulidSuccess();
    }

    public function del()
    {
        if (!($id = $this->post('id')) || !is_numeric($id)) {
            return static::bulidFail('ID错误');
        }

        if (!$model = AdsModel::where('id', $id)->find()) {
            return static::bulidFail('不存在的广告 请勿非法操作');
        }

        if (!$model->delete()) {
            return static::bulidFail('删除失败');
        }

        $this->addAdminLog("删除了广告，ID：{$model->id}");

        return static::bulidSuccess('已删除');
    }

    public function appadd()
    {
        return $this->assign([
            'type'      => Request::param('type'),
            'type_cate' => AdsModel::TYPE_CATE
        ])->fetch();
    }

    public function appedit()
    {
        return $this->assign(['adsInfo' => AdsModel::get(Request::param('id'))])->fetch();
    }

    public function signForCos()
    {
        return parent::signForCos();
    }

    public function getlist()
    {
        $type = Request::param("type");
        $ads  = AdsModel::where(["type" => $type])->order("create_time desc")->select();
        if (count($ads)) {
            return self::bulidSuccess($ads);
        }
        return self::bulidFail("未查询到相关数据");
    }

    public function opt_post()
    {
        $id  = Request::param('id');
        $ads = AdsModel::get($id);
        if (!$ads) {
            return self::bulidFail("广告条目不存在");
        }

        $status = $ads->status == 1 ? 0 : 1;
        if ($ads->save(["status" => $status])) {
            // 记录日志
            $log_txt     = $ads->status == 1 ? '生效' : '失效';
            $log_content = "设置{$ads->type_text}为{$log_txt}，ID：{$ads->id}";
            parent::addAdminLog($log_content);

            return self::bulidSuccess([]);
        }
        return self::bulidFail();
    }

    public function appadd_post()
    {
        $ads              = new AdsModel(Request::param());
        $ads->create_time = date("Y-m-d H:i:s");
        $ads->end_time    = time();
        $ads->start_time  = time();
        $ads->equipment   = 1;
        $ads->type        = 9;
        if ($ads->save()) {
            // 记录日志
            $log_content = "添加{$ads->type_text}，ID：{$ads->id}，标题：{$ads->title}，url：{$ads->image_url}";
            parent::addAdminLog($log_content);

            return self::bulidSuccess([]);
        }
        return self::bulidFail();
    }

    public function appedit_post()
    {
        $ads = AdsModel::get(Request::param('id'));
        if (!$ads) {
            return self::bulidFail("广告条目不存在");
        }
        if ($ads->save(Request::param())) {
            // 记录日志
            $log_content = "编辑{$ads->type_text}，ID：{$ads->id}，标题：{$ads->title}，url：{$ads->image_url}";
            parent::addAdminLog($log_content);

            return self::bulidSuccess();
        }
        return self::bulidFail();
    }

    public function appdel_post()
    {
        $id  = Request::param('id');
        $ads = AdsModel::get($id);
        if (!$ads) {
            return self::bulidFail("广告条目不存在");
        }

        if (AdsModel::destroy($id)) {
            // 记录日志
            $log_content = "删除{$ads->type_text}，ID：{$ads->id}，标题：{$ads->title}，url：{$ads->image_url}";
            parent::addAdminLog($log_content);

            return self::bulidSuccess();
        }
        return self::bulidFail();
    }
}
